#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Author: kindey
@Date: 2025/8/27
@Description: 一个尝试可行性的服务，不知道要干什么
"""
import logging
import numpy as np
import featuretools as ft
import pandas as pd
from tsfresh import extract_features,select_features
from tsfresh.utilities.dataframe_functions import impute
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

class XServiceOne:
    logger = logging.getLogger(__name__)
    def x_service_one(self):
        self.logger.info("x_service_one")
        return "x_service_one"

    @staticmethod
    def x_learn_sklearn():
        X = np.array([[2, 3, 4],
                      [5, 6, 7]])
        # 创建一个PolynomialFeatures转换器
        # degree=2: 生成最高二次项
        # include_bias=False: 不包含偏置项(常数1)
        poly = PolynomialFeatures(degree=2, include_bias=False)

        # 拟合和转换数据
        X_poly = poly.fit_transform(X)

        logging.info("原始特征名 (假设): [a, b, c]")
        logging.info("原始数据:\n%s", X)
        logging.info("-" * 30)
        logging.info("自动提取的特征名: %s", poly.get_feature_names_out(['a', 'b', 'c']))
        logging.info("提取后的数据:\n%s", X_poly)

    @staticmethod
    def x_learn_featuretools():
        # 1. 创建示例数据
        customers_df = pd.DataFrame({
            "customer_id": [1, 2, 3],
            "join_date": pd.to_datetime(["2022-01-01", "2022-02-15", "2022-03-10"]),
            "city": ["New York", "London", "New York"]
        })

        transactions_df = pd.DataFrame({
            "transaction_id": range(6),
            "customer_id": [1, 1, 2, 2, 3, 1],
            "amount": [100, 50, 200, 75, 120, 80],
            "transaction_time": pd.to_datetime([
                "2022-01-10", "2022-02-05", "2022-03-01", "2022-03-20",
                "2022-03-15", "2022-04-01"
            ])
        })

        # 2. 创建一个实体集 (EntitySet)
        es = ft.EntitySet(id="my_store")

        # 3. 将DataFrame添加为实体
        es = es.add_dataframe(dataframe_name="customers", dataframe=customers_df, index="customer_id")
        es = es.add_dataframe(dataframe_name="transactions", dataframe=transactions_df,
                              make_index=False, index="transaction_id",
                              time_index="transaction_time")

        # 4. 定义实体间的关系
        es = es.add_relationship("customers", "customer_id", "transactions", "customer_id")

        # 5. 运行深度特征合成 (DFS)
        # target_dataframe_name="customers"意味着我们想为每个customer生成特征
        feature_matrix, feature_defs = ft.dfs(entityset=es,
                                              target_dataframe_name="customers",
                                              agg_primitives=["sum", "mean", "count", "std"],  # 聚合操作
                                              trans_primitives=["month", "weekday","time_since_previous"])  # 转换操作

        logging.info("为每个客户自动提取的特征矩阵:")
        logging.info(feature_matrix)

        # 打印出一些被创建的特征名字
        print("\n部分特征名称:")
        for f in feature_defs[-5:]:
            logging.info(f.get_name())

    @staticmethod
    def x_learn_tsfresh():
        # 1. 创建更复杂的时间序列数据示例
        np.random.seed(42)
        time_series_data = []
        labels = []

        # 生成不同类型的时间序列数据
        for i in range(50):
            # 类型1：趋势上升序列
            if i < 25:
                trend = np.linspace(0, 100, 100)  # 线性增长趋势
                noise = np.random.normal(0, 5, 100)  # 噪声
                values = trend + noise
                label = 0  # 标签：趋势上升
            # 类型2：周期性序列
            else:
                periodic = 50 * np.sin(np.linspace(0, 4 * np.pi, 100))  # 正弦波
                noise = np.random.normal(0, 5, 100)
                values = periodic + noise
                label = 1  # 标签：周期性

            # 构造时间序列数据
            for t, value in enumerate(values):
                time_series_data.append({
                    'id': i,
                    'time': t,
                    'value': value
                })
            labels.append({'id': i, 'label': label})

        # 转换为DataFrame
        df = pd.DataFrame(time_series_data)
        labels_df = pd.DataFrame(labels)

        # 2. 提取时间序列特征
        print("正在提取时间序列特征...")
        extracted_features = extract_features(df, column_id='id', column_sort='time')

        # 处理缺失值
        impute(extracted_features)

        # 3. 特征选择（选择与标签相关的特征）
        print("正在进行特征选择...")
        selected_features = select_features(extracted_features, labels_df['label'])

        # 4. 准备训练数据
        X_train, X_test, y_train, y_test = train_test_split(
            selected_features, labels_df['label'],
            test_size=0.3, random_state=42
        )

        # 5. 使用随机森林分类器训练
        clf = RandomForestClassifier(n_estimators=50, random_state=42)
        clf.fit(X_train, y_train)

        # 6. 预测和评估
        y_pred = clf.predict(X_test)
        print("\n分类结果报告:")
        print(classification_report(y_test, y_pred))

        # 7. 显示一些区分度高的特征
        feature_importance = pd.DataFrame({
            'feature': X_train.columns,
            'importance': clf.feature_importances_
        }).sort_values('importance', ascending=False)

        print("\n前10个最重要的特征:")
        print(feature_importance.head(10))